// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*************************************************************************
 * @file SimpleSubscriber.cpp
 * This file contains the implementation of the subscriber functions.
 *
 * This file was generated by the tool fastrtpsgen.
 */


#include "SimpleSubscriber.h"
#include "SimplePubSubType.h"

SimpleSubscriber::SimpleSubscriber() : mp_RTPSParticipant(NULL), mp_subscriber(NULL) {}

SimpleSubscriber::~SimpleSubscriber() {}

bool SimpleSubscriber::init()
{
	// Create RTPSParticipant
	
	RTPSParticipantAttributes PParam;
	PParam.builtin.domainId = 80; //MUST BE THE SAME AS IN THE PUBLISHER
	TIME_INFINITE(PParam.builtin.leaseDuration);
	PParam.name = "RTPSParticipant_subscriber"; //You can put the name you want
	mp_RTPSParticipant = RTPSDomain::createRTPSParticipant(PParam);
	if(mp_RTPSParticipant == NULL)
			return false;
			
	// Create Subscriber
			
	SubscriberAttributes Rparam;
	Rparam.topic.topicKind = NO_KEY;
	Rparam.topic.topicDataType = "SimpleStructPubSubType"; //Must be registered before the creation of the subscriber
	Rparam.topic.topicName = "SimplePubSubTopic";
	mp_subscriber = RTPSDomain::createSubscriber(mp_RTPSParticipant,Rparam,(SubscriberListener*)&m_listener);
	if(mp_subscriber == NULL)
		return false;
	m_listener.mp_sub = mp_subscriber; //We copy the pointer to the subscriber to be able to read and take data from the listener directly
	return true;
}

void SimpleSubscriber::SubListener::onSubscriptionMatched(MatchingInfo info)
{
	if (info.status == MATCHED_MATCHING)
	{
		n_matched++;
		cout << "Subscriber matched" << endl;
	}
	else
	{
		n_matched--;
		cout << "Subscriber unmatched" << endl;
	}
}

void SimpleSubscriber::SubListener::onNewDataMessage()
{
	if(mp_sub!=NULL)
	{
		// Take data
		SimpleStruct st;
		
		if(mp_sub->takeNextData(&st, &m_info))
		{
			if(m_info.sampleKind == ALIVE)
			{
				// Print your structure data here.
			}
		}

	}
}

void SimpleSubscriber::run()
{
	cout << "Type something and press enter to stop the subscriber: "<<endl;
	int aux;
	std::cin >> aux;
}

